package cn.ctyun.ipush.controller;

import cn.ctyun.ipush.constant.ResultInfo;
import cn.ctyun.ipush.dto.ResultDto;
import cn.ctyun.ipush.model.DsDictionaryModel;
import cn.ctyun.ipush.model.DataSourceModel;
import cn.ctyun.ipush.service.DataSourceService;
import cn.ctyun.ipush.utils.DBUtils;
import cn.ctyun.ipush.utils.DataUtils;
import cn.ctyun.ipush.utils.DateUtils;
import cn.ctyun.ipush.vo.DataSourceVo;
import cn.ctyun.ipush.web.user.bo.UserModel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dexcoder.dal.JdbcDao;
import com.dexcoder.dal.build.Criteria;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * Created by yanghongbo on 2016/7/4.
 */
@Controller
@RequestMapping
public class RuleController {

    /* 日志对象 */
    private final Logger LOG = LoggerFactory.getLogger(RuleController.class);

    @Autowired
    private DataSourceService dataSourceService;

    @Autowired
    private JdbcDao jdbcDao;

    /**
     * 用于进入页面后，显示数据,以及删除数据后重新展现数据
     */
    @RequestMapping(value = "ruleIntoPage", method = RequestMethod.GET)
    public ModelAndView intoPage(HttpSession session, HttpServletRequest request) {

        UserModel systemUserModel = new UserModel();

        String msg = "";
        try {
            Object o = session.getAttribute("userInfo");

            if (o != null) {
                systemUserModel = (UserModel) o;

                //是否是删除操作
                String method = request.getParameter("method");
                if (!StringUtils.isEmpty(method)) {
                    if (method.equals("delete")) {
                        String dataSourceId = request.getParameter("dataId");
                        if (!StringUtils.isEmpty(dataSourceId)) {
                            if (dataSourceService.delete(dataSourceId) == 0) {
                                msg = "该数据源在任务中有引用不能删除,请先删除任务，在进行删除";
                            }
                        }
                    }
                }
                //获取并展现数据
                DataSourceModel tmpDataSourceModel = new DataSourceModel();
                tmpDataSourceModel.setCreateUserid(systemUserModel.getUserModelId());
                List<DataSourceModel> dataSourceModelList = dataSourceService.queryList(tmpDataSourceModel);
                //判断是否存在对应的数据源，没有的话，从数据源码表中添加
                if(dataSourceModelList.size()<1){
                    //创建数据源
                    String cityId=systemUserModel.getCity();
                    DsDictionaryModel dsDictionaryModel =new DsDictionaryModel();
                    dsDictionaryModel.setCityId(cityId);
                    Criteria criteria=Criteria.select(DsDictionaryModel.class).where("cityId",new Object[]{dsDictionaryModel.getCityId()});
                    List<DsDictionaryModel> dsDictionaryModelList =jdbcDao.queryList(criteria);
                    if(dsDictionaryModelList.size()>0){
                        for (DsDictionaryModel dsm: dsDictionaryModelList){
                            DataSourceModel dataSourceModel=new DataSourceModel();
                            dataSourceModel.setCreateUserid(systemUserModel.getUserModelId());
                            dataSourceModel.setCreateDate(DateUtils.dateToString(new Date()));
                            dataSourceModel.setIsDeleted("0");
                            dataSourceModel.setDataSourceName(dsm.getDataSourceName());
                            dataSourceModel.setDataSourceUrl(dsm.getDataSourceUrl());
                            dataSourceModel.setUserName(dsm.getUserName());
                            dataSourceModel.setDsPassword(dsm.getDsPassword());
                            dataSourceModel.setConnMaxCount("10");
                            dataSourceService.save(dataSourceModel);
                            dataSourceModelList.add(dataSourceModel);
                        }
                    }
                }
                int index = 1;
                Map<String, List> map = new LinkedHashMap<String, List>();
                if (dataSourceModelList != null) {
                    for (DataSourceModel dataSourceModel : dataSourceModelList) {
                        List list = new ArrayList();
                        list.add(index++);
                        list.add(dataSourceModel.getDataSourceName());
                        list.add(dataSourceModel.getDataSourceUrl());
                        list.add(systemUserModel);
                        list.add(dataSourceModel.getUserName());
                        list.add(dataSourceModel.getDataSourceModelId());

                        map.put(dataSourceModel.getDataSourceModelId(), list);
                    }
                }
                Map<String, Object> data = new HashMap<String, Object>();
                data.put("ruleMap", map);
                data.put("msg", msg);
                return new ModelAndView("ruleManager", data);
            } else {
                //没有登录。。。。跳回login
                return new ModelAndView("login", null);
            }
        } catch (Exception e) {
            LOG.error(e.getMessage());
            //没有登录。。。。跳回login
            return new ModelAndView("login", null);
        }
    }

    /**
     * 用户检测配置的数据库信息是否可以连接
     */
    public boolean checkAddDataSource(String url, String username, String userPassword, String tableName) {
        ResultDto resultDto = DBUtils.isConectionSuccess(url, username, userPassword, tableName);
        if (resultDto.getStatus().equals(ResultInfo.success)) {
            return true;
        } else {
            return false;
        }
    }

    @RequestMapping(value = "checkDsTableIsExist", method = RequestMethod.POST)
    @ResponseBody
    public ResultDto checkDsTableIsExist(HttpServletRequest request) {
        String requestJsonParam = DataUtils.getJsonFromRequest(request);
        ResultDto resultDto = new ResultDto();
        if (StringUtils.isEmpty(requestJsonParam)) {
            return resultDto.setStatus(ResultInfo.failure).setInfo("测试连接失败，请检查参数是否配置正确");
        } else {
            try {
                JSONObject jsonObject = JSON.parseObject(requestJsonParam);
                String dsId = jsonObject.getString("dataSourceId");
                String dataTable = jsonObject.getString("addTableName");
                DataSourceModel dataSourceModel = dataSourceService.querySingleResult(dsId);
                if (null != dataSourceModel) {
                    boolean isExist = checkAddDataSource(dataSourceModel.getDataSourceUrl(), dataSourceModel.getUserName(), dataSourceModel.getDsPassword(), dataTable);
                    if (isExist) {
                        return resultDto.setStatus(ResultInfo.success).setInfo("测试连接成功");
                    } else {
                        return resultDto.setStatus(ResultInfo.failure).setInfo("测试连接失败，请检查参数是否配置正确");
                    }
                } else {
                    return resultDto.setStatus(ResultInfo.failure).setInfo("测试连接失败，请检查参数是否配置正确");
                }

            } catch (Exception ex) {
                LOG.info("测试连接失败：" + ex.getMessage());
                return resultDto.setStatus(ResultInfo.failure).setInfo("测试连接失败，请检查参数是否配置正确");
            }
        }
    }

    @RequestMapping(value = "checkDsIsExist", method = RequestMethod.POST)
    @ResponseBody
    public ResultDto checkDsIsExist(HttpServletRequest request) {
        String requestJsonParam = DataUtils.getJsonFromRequest(request);
        ResultDto resultDto = new ResultDto();
        if (StringUtils.isEmpty(requestJsonParam)) {
            return resultDto.setStatus(ResultInfo.failure).setInfo("测试连接失败，请检查参数是否配置正确");
        } else {
            try {
                JSONObject jsonObject = JSON.parseObject(requestJsonParam);
                boolean isExist = checkAddDataSource((String) jsonObject.get("dataURL"), (String) jsonObject.get("dataLoginName"), (String) jsonObject.get("dataPassword"), null);
                if (isExist) {
                    return resultDto.setStatus(ResultInfo.success).setInfo("测试连接成功");
                } else {
                    return resultDto.setStatus(ResultInfo.failure).setInfo("测试连接失败，请检查参数是否配置正确");
                }
            } catch (Exception ex) {
                LOG.info("测试连接失败：" + ex.getMessage());
                return resultDto.setStatus(ResultInfo.failure).setInfo("测试连接失败，请检查参数是否配置正确");
            }
        }
    }

    /**
     * 加载TABLE，显示数据并且4个一行显示
     */
    @RequestMapping(value = "iniRuleTable", method = RequestMethod.GET)
    public ModelAndView iniRuleTable(HttpSession session, HttpServletRequest request) {

        UserModel systemUserModel = new UserModel();
        try {
            Object o = session.getAttribute("userInfo");
            if (o != null) {
                systemUserModel = (UserModel) o;///得到USER

                String dataSourceId = request.getParameter("dataId");//得到这个database 名字

                //是否删除表
                String[] tableNameLists = request.getParameterValues("tableNameList");
                if (null != tableNameLists) {
                    DataSourceModel dataSourceModel = dataSourceService.querySingleResult(dataSourceId);
                    String tableList = dataSourceModel.getSqlListDb();
                    String resultTable = "";
                    for (String table : tableList.split("\\$")) {
                        boolean isExist = false;
                        for (String tmpTable : tableNameLists) {
                            if (table.equals(tmpTable)) {
                                isExist = true;
                                break;
                            }
                        }
                        if (!isExist) {
                            resultTable += (table + "$");
                        }
                    }
                    if (!resultTable.equals("")) {
                        resultTable = resultTable.substring(0, resultTable.length() - 1);
                    }
                    dataSourceModel.setSqlListDb(resultTable);
                    dataSourceService.update(dataSourceModel);
                }

                // create user + dataname 确定一个 datasource
                //查出来这个datasource所有的tablename
                List<String> tableList = new ArrayList<String>();
                DataSourceModel dataSourceModel = dataSourceService.querySingleResult(dataSourceId);
                String tables = dataSourceModel.getSqlListDb();

                List<List<String>> resultList = new ArrayList<List<String>>();
                if (tables != null) {
                    for (String table : tables.split("\\$")) {
                        tableList.add(table);
                    }
                    //组成一个二维数据
                    List<String> siteList = null;
                    for (int i = 0; i < tableList.size(); i++) {
                        if (i % 4 == 0) {
                            if (i != 0) {
                                resultList.add(siteList);
                            }
                            siteList = new ArrayList<String>();
                            siteList.add(tableList.get(i));
                        } else {
                            siteList.add(tableList.get(i));
                        }
                    }
                    resultList.add(siteList);
                }

                Map<String, Object> data = new HashMap<String, Object>();
                data.put("tableName", resultList);
                data.put("dataId", dataSourceId);
                return new ModelAndView("ruleDataTable", data);
            } else {
                //没有登录。。。。跳回login
                return new ModelAndView("login", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            //没有登录。。。。跳回login
            return new ModelAndView("login", null);
        }

    }

    @RequestMapping(value = "ruleDataAdd", method = RequestMethod.POST)
    public ModelAndView ruleDataAdd(HttpSession session, HttpServletRequest request) {
        DataSourceVo dataSoureVo = new DataSourceVo();
        String msg = "";
        //添加到dataSourceVo中
        UserModel systemUserModel = null;
        try {
            Object o = session.getAttribute("userInfo");
            boolean isSave = true;
            if (o != null) {
                systemUserModel = (UserModel) o;
                //判断是否为空
                String dataSourceName = request.getParameter("dataName");
                if (StringUtils.isEmpty(dataSourceName)) {
                    msg = "数据源名不为能空";
                    isSave = false;
                } else {
                    dataSoureVo.setDataSourceName(dataSourceName);
                }

                String dataURL = request.getParameter("dataURL");
                if (StringUtils.isEmpty(dataURL)) {
                    msg = "数据源中URL不能为空";
                    isSave = false;
                } else {
                    dataSoureVo.setDataSourceUrl(dataURL);
                }

                String dataLoginName = request.getParameter("dataLoginName");
                if (StringUtils.isEmpty(request.getParameter("dataLoginName"))) {
                    msg = "数据源中登陆名不能为空";
                    isSave = false;
                } else {
                    dataSoureVo.setUserName(dataLoginName);
                }

                String dataPassword = request.getParameter("dataPassword");
                if (StringUtils.isEmpty(request.getParameter("dataPassword"))) {
                    msg = "数据源中密码不能为空";
                    isSave = false;
                } else {
                    dataSoureVo.setDsPassword(dataPassword);
                }

                //测试连接是否可行
                ResultDto resultDto = DBUtils.isConectionSuccess(dataURL, dataLoginName, dataPassword, null);
                if (!resultDto.getStatus().equals(ResultInfo.success)) {
                    msg = "连接失败:" + resultDto.getInfo();
                    isSave = false;
                }
                //保存数据到数据库
                if (isSave) {
                    //数据源名称不能为已经存在的
                    if (!dataSourceService.isExist(dataSoureVo)) {
                        dataSoureVo.setCreateUserid(systemUserModel.getUserModelId());
                        dataSourceService.save(dataSoureVo);
                    } else {
                        msg = "数据源名已存在";
                    }
                }

                //得到当前用户的所有数据源数据

                Map<String, List> map = new LinkedHashMap<String, List>();
                DataSourceModel tmpDataSourceModel = new DataSourceModel();
                tmpDataSourceModel.setCreateUserid(systemUserModel.getUserModelId());
                List<DataSourceModel> dataSourceModelList = dataSourceService.queryList(tmpDataSourceModel);
                int index = 1;
                if (dataSourceModelList != null) {
                    for (DataSourceModel dataSourceModel : dataSourceModelList) {

                        List list = new ArrayList();
                        list.add(index++);
                        list.add(dataSourceModel.getDataSourceName());
                        list.add(dataSourceModel.getDataSourceUrl());
                        list.add(systemUserModel);
                        list.add(dataSourceModel.getUserName());
                        list.add(dataSourceModel.getDataSourceModelId());
                        map.put(dataSourceModel.getDataSourceModelId(), list);
                    }
                }


                Map<String, Object> data = new HashMap<String, Object>();
                data.put("ruleMap", map);
                data.put("msg", msg);
                return new ModelAndView("ruleManager", data);
            } else {
                //没有登录。。。。跳回login
                return new ModelAndView("login", null);
            }
        } catch (Exception ex) {
            LOG.error("保存数据源信息失败，消息：" + ex.getMessage());
            return new ModelAndView("login", null);
        }
    }


    /**
     * 加载TABLE，显示数据并且4个一行显示
     */
    @RequestMapping(value = "ruleTableAdd", method = RequestMethod.POST)
    public ModelAndView ruleTableAdd(HttpSession session, HttpServletRequest request) {

        //算法详情
        //1、取出session 中的USER 查询dataSource 中的createUser
        //2、查询出来是一个LIST 粒度是表
        //3、根据数据库名、URL、数据库用户名 去重
        //4、多个表 合成一个LIST 返回
        UserModel systemUserModel = new UserModel();
        String tableAddMsg = "";
        try {
            Object o = session.getAttribute("userInfo");
            if (o != null) {
                systemUserModel = (UserModel) o;///得到USER
                boolean isSave = true;

                //判断表名是否为空
                String addTableName = request.getParameter("addTableName");
                String dataSourceId = request.getParameter("dataSourceId");//得到这个database 名字
                DataSourceModel dataSourceModel = dataSourceService.querySingleResult(dataSourceId);
                DataSourceModel dataSourceModeltmp = dataSourceService.querySingleResult(dataSourceId);

                if (StringUtils.isEmpty(addTableName)) {
                    tableAddMsg = "增加的表名为空";
                    isSave = false;
                } else {
                    //检测这个表是否存在
                    ResultDto resultDto = DBUtils.isConectionSuccess(dataSourceModeltmp.getDataSourceUrl(), dataSourceModeltmp.getUserName(), dataSourceModeltmp.getDsPassword(), addTableName);
                    if (resultDto.getStatus().equals(ResultInfo.failure)) {
                        isSave = false;
                        tableAddMsg = "表不存在";
                    }
                    if (isSave) {
                        //增加这个表到DB
                        String tables = dataSourceModel.getSqlListDb();
                        if (tables == null || StringUtils.isEmpty(tables)) {
                            dataSourceModel.setSqlListDb(addTableName);
                            dataSourceService.update(dataSourceModel);
                        } else {
                            //判断表名是否重复
                            boolean isTableNameSame = false;
                            for (String existTableName : tables.split("\\$")) {
                                if (existTableName.equals(addTableName)) {
                                    isTableNameSame = true;
                                    break;
                                }
                            }
                            if (!isTableNameSame) {
                                dataSourceModel.setSqlListDb(tables + "$" + addTableName);
                                dataSourceService.update(dataSourceModel);
                            } else {
                                tableAddMsg = "增加的表名已经存在";
                            }
                        }

                    }
                }

                //查出来这个datasource所有的tablename
//                List<String> tableList = new ArrayList<String>();
//                List<List<String>> resultList = new ArrayList<List<String>>();
//                if (dataSourceModel.getSqlListDb() != null) {
//                    for (String table : dataSourceModel.getSqlListDb().split("\\$")) {
//                        tableList.add(table);
//                    }
//                    //组成一个二维数据
//                    List<String> siteList = null;
//                    for (int i = 0; i < tableList.size(); i++) {
//                        if (i % 4 == 0) {
//                            if (i != 0) {
//                                resultList.add(siteList);
//                            }
//                            siteList = new ArrayList<String>();
//                            siteList.add(tableList.get(i));
//                        } else {
//                            siteList.add(tableList.get(i));
//                        }
//                    }
//                    resultList.add(siteList);
//                }
//
//                Map<String, Object> data = new HashMap<String, Object>();
                // data.put("tableName", resultList);
                //data.put("dataId", dataSourceId);
                //  data.put("msg",tableAddMsg);
                //获取并展现数据
                DataSourceModel tmpDataSourceModel = new DataSourceModel();
                tmpDataSourceModel.setCreateUserid(systemUserModel.getUserModelId());
                List<DataSourceModel> dataSourceModelList = dataSourceService.queryList(tmpDataSourceModel);
                int index = 1;
                Map<String, List> map = new LinkedHashMap<String, List>();
                if (dataSourceModelList != null) {
                    for (DataSourceModel dataSourceModel1 : dataSourceModelList) {
                        List list = new ArrayList();
                        list.add(index++);
                        list.add(dataSourceModel1.getDataSourceName());
                        list.add(dataSourceModel1.getDataSourceUrl());
                        list.add(systemUserModel);
                        list.add(dataSourceModel1.getUserName());
                        list.add(dataSourceModel1.getDataSourceModelId());

                        map.put(dataSourceModel1.getDataSourceModelId(), list);
                    }
                }
                Map<String, Object> data = new HashMap<String, Object>();
                data.put("ruleMap", map);
                data.put("msg", tableAddMsg);
                return new ModelAndView("ruleManager", data);
            } else {
                //没有登录。。。。跳回login
                return new ModelAndView("login", null);
            }
        } catch (Exception e) {
            LOG.error(e.getMessage());
            //没有登录。。。。跳回login
            return new ModelAndView("login", null);
        }
    }
}